<script>
/* Global variables */
var last_value='';  /* 缓存输入区文字 */
var prepo={};       /* 存储每行文字和拼音，以前缀数字为健值 */
var g_work_types = ['诗','词','文','曲'];
var g_yl = ['平', '仄'];
var g_context_menu = {
name: [{item:'编辑名称', code:'wz'},{item:'注释', code:'zs'}],
author: [{item:'编辑作者', code:'wz'}],
preface: [{item:'编辑序言', code:'wz'}, {item:'注释', code:'zs'}, {item:'前插新行', code:'new_before'},{item:'后插新行', code:'new_after'}, {item:'删除此行', code:'del'}],
lines: [{item:'编辑正文', code:'wz'}, {item:'注释', code:'zs'}, {item:'韵律', code:'yl'}, {item:'译文', code:'yw'}, {item:'前插新行', code:'new_before'},{item:'后插新行', code:'new_after'},{item:'删除此行', code:'del'}],
tag: [{item:'编辑标签', code:'wz'}],
analyse: [{item:'编辑赏析', code:'wz'}] 
}

// 创建新作品入口
function new_work() {
    var work = blank_work(); 
    init_cache(work);
    show_work_editor(work);
    editor_event_handler();
}

// 编辑作品入口
function edit_work(work) {
    init_cache(work);
    show_work_editor(work);
    editor_event_handler();
}

// 显示作品编辑器界面
function show_work_editor(work) {
  let param = set_param(work);
  let html = template('template_editor', param);
  $('#modal_content').html(trans_text(html));
  $('#modal').trigger('md_show');
  hide_wzylzsyw_container();
}

function hide_wzylzsyw_container() {
  // 缺省隐藏韵律、注释和译文编辑区
  ['.yl_container', '.zs_container','.yw_container'].forEach(function(item) {
     $(item).hide();
  });
  // 显示/隐藏文字输入框 不显示拼音的文字输出和输入同框因此一直显示
  $('.wz_ip_container').each(function(i,c) {
    (($(c).find('.wz_ip').attr('data_show_py') == 'true') && $(c).find('.wz_ip')[0].value.trim().length) ? $(c).hide():$(c).show();
  });
}

// 保存当前编辑作品到服务器上的作品库中
function save_new() {
    var url = "/v1/save";
    var work = restore_cache(dp=false); 
    ret = check_work(work);
    if (ret.trim().length) {
        alert(ret);
        return;
    }
    spinner_start();
    $.post(url, {_xsrf:$.cookie('_xsrf'), work:JSON.stringify(work)}).done(function(data, status) {
        //console.log("data: \n" + data + "\nstatus: " + status);
        $('#modal').trigger('md_close');
    }).fail(function(jqXHR, textStatus, errorThrown) {
        console.log("保存作品详失败: " + textStatus + ": " + errorThrown );
    }).always(function() {
        spinner_stop();
    });
}

// 检查作品必须条目是否满足 
function check_work(work) {
    // console.log("Check ", work);
    return work.name.trim().length?(work.author.trim().length?(work.type.trim().length?(work.lines.length?(''):"请录入作品正文"):"请录入作品分类"):"请录入作者姓名"):"请录入作品名称"; 
}

// 作品编辑器头部 - 预览/编辑作品功能的统一入口
function preview_edit(obj) {
    $.t2s($('#preview_edit').text().trim()) == "预览"?pe_preview(obj):pe_edit(obj);
}

// 预览当前编辑作品
function pe_preview(obj) {
    var work = restore_cache(); 
    // console.log("[pe preview] cache", prepo);
    // console.log("[pe preview] restored work", work);
    ret = check_work(work);
    if (ret.trim().length) {
        alert(ret);
        return;
    }
    work.mark = "pinyin";
    work.cnum = cnum;
    var html = template('template_work_detail_body', work);
    $('#editor_body').html(trans_text(html));
    $('#preview_edit').text(trans_text("编辑"));
    $('#preview_edit').attr('title',trans_text("编辑作品"));
    show_body_event_handler();
}

// 退出预览回到作品编辑界面
function pe_edit(obj) {
    var work = restore_cache();
    var param = set_param(work);
    var html = template('template_editor_body', param);
    $('#editor_body').html(trans_text(html));
    $('#preview_edit').text(trans_text("预览"));
    $('#preview_edit').attr('title',trans_text("预览作品"));

    hide_wzylzsyw_container();

    // 添加编辑器事件处理器
    editor_body_event_handler();
}

// 在服务器上的作品库中删除指定作品 
function del_work(id) {
    var url = "/v1/del";
    if (!confirm(trans_text("作品删除后不能再恢复，确认删除此作品？"))) return;
    // console.log("id: " + id);
    spinner_start();
    $.post(url, {_xsrf:$.cookie('_xsrf'), id:id}).done(function(data, status) {
        // console.log("data: \n" + data + "\nstatus: " + status);
        $('#modal').trigger('md_close');
    }).fail(function(jqXHR, textStatus, errorThrown) {
        console.log("删除作品失败: " + textStatus + ": " + errorThrown );
    }).always(function() {
        spinner_stop();
    });
}

// 根据提供的作品信息初始化缓存
function init_cache(work) {
   // 清空缓存 
   for ( var key in prepo ) delete prepo[key]; 
   if ( ! work ) { 
     return; 
   }

   ['name', 'author', 'preface', 'lines'].forEach(function(key) {
       prepo[key] = [];
       let pkey= `p${key}`;
       let dpkey= `dp${key}`;
       work[key].split('\n').forEach(function(item, index){
         prepo[key][index] = {};
         prepo[key][index]['text'] = item;
         prepo[key][index]['dan_pinyin'] = work[pkey][index];
         prepo[key][index]['duo_pinyin'] = [];
       });
   });
   ['id', 'type', 'category', 'tag', 'comment', 'analyse'].forEach(function(key, index) {
       prepo[key] = work[key];
   });
}

// 从缓存中提取作品信息
function restore_cache(dp=true) {
   var work = blank_work(dp);
   //work.id = prepo.id.trim().length?prepo.id.trim():md5(prepo.name.trim() + prepo.author.trim() + prepo.lines.trim());
   work.id = prepo.id.trim().length?prepo.id.trim():GUID();

  ['name', 'author', 'preface', 'lines'].forEach(function(key) {
    var text = '';
    if (key in prepo && prepo[key].length ) {
      for ( var index in prepo[key] ) {
        text += prepo[key][index].text + "\n";
        work[`p${key}`][index] = prepo[key][index].dan_pinyin;
        if (dp) work[`dp${key}`][index] = prepo[key][index].duo_pinyin;
      }
    }
    work[key] = text.trim();
  });

/*
   // 作品名称应该是没有换行，只是按统一风格处理
   var name = '';
   if ('name' in prepo && prepo.name.length ) {
     for ( var index in prepo.name ) { 
       name += prepo['name'][index].text + "\n";
       work['pname'][index] = prepo['name'][index].dan_pinyin;
       if(dp) work['dpname'][index] = prepo['name'][index].duo_pinyin;
    }
   }
   work['name'] = name.trim();
   // 作者姓名应该是没有换行，只是按统一风格处理
   var author = '';
   if ('author' in prepo && prepo.author.length ) {
     for ( var index in prepo.author ) {
       author += prepo['author'][index].text + "\n";
       work['pauthor'][index] = prepo['author'][index].dan_pinyin;
       if(dp) work['dpauthor'][index] = prepo['author'][index].duo_pinyin;
    }
   }
   work['author'] = author.trim();
   var preface = '';
   if ('preface' in prepo && prepo.preface.length ) {
     for ( var index in prepo.preface ) {
       preface += prepo['preface'][index].text + "\n";
       work['ppreface'][index] = prepo['preface'][index].dan_pinyin;
       if(dp) work['dppreface'][index] = prepo['preface'][index].duo_pinyin;
    }
   }
   work['preface'] = preface.trim();
   var lines = '';
   if ('lines' in prepo && prepo.lines.length ) {
       for ( var index in prepo.lines ) {
           lines += prepo['lines'][index].text + '\n';
           work['plines'][index] = prepo['lines'][index].dan_pinyin;
           if(dp) work['dplines'][index] = prepo['lines'][index].duo_pinyin;
       }
   }
   work['lines'] = lines.trim();
*/

   ['type', 'category', 'tag', 'analyse', 'comment'].forEach(function(key, index) {
       work[key] = prepo[key];
   });
   // 自动将作品名称、作者、类型、分类加入标签中
   [work['name'], work['author'], work['type'], work['category']].forEach(function(key, index) {
       key = remove_nonchinese(key);
       if ( key.length && work['tag'].indexOf(key) == -1 ) work['tag'].push(key);
   });

   return work;
}

function is_blank_cache() {
    var ret = true;
    if ( Object.keys(prepo).length ) {
        if (prepo.name.length || prepo.author ) ret = false;
    }
    return ret;
} 

function blur(event, obj) {
    let id = $(obj).attr('data_id');
    if ( id == 'tag' || id == 'analyse' ) return;
    if (obj.value.trim().length) $(obj).parent().hide();
}

/*
 * 文字输入区事件处理函数
 * 当在文字输入框中输入字符时触发此处理函数 - 框中无字符则清空拼音显示区域，如果输入区无变化则返回，否则向服务器获取拼音并显示在拼音显示区，如果是回车事件并且输入区是单行文本输入区则隐藏输入区
 */
function key_pressed(event, obj) {
    let id = $(obj).attr('data_id'), uuid = obj.id, index = $(obj).attr('data_index');
    let show_py = $(obj).attr('data_show_py') == 'true' ? true : false;
    let show_zs = $(obj).attr('data_show_zs') == 'true' ? true : false;
    let show_yl = $(obj).attr('data_show_yl') == 'true' ? true : false;
    let text = $.t2s(obj.value.trim());
    //console.log(id, uuid, index, text, show_py, show_zs, show_yl);
    //console.log(obj);

    if ( last_value != text ) {
        last_value = text;

        // 从服务器得到文字的拼音和注释，并显示在相应的容器上 
        let param = {id:id, uuid:uuid, index:index, text:text};
        if ( show_py ) get_pinyin(param); 
        if ( show_zs ) get_comment(param); 
        if ( show_yl ) get_yl(param);
        // 留待今后优化，暂按现在数据格式 tag - 数组analyse - 字符串, 以后可统一为字符串 
        if (id == 'tag') prepo['tag'] = text.split(' ');
        if (id == 'analyse') prepo['analyse'] = text; 
    }

    /* 回车换新行 - 正文和序言则插入新行 */
    if ((event.keyCode || event.which ) == key_Enter) {
       let data = {uuid:uuid, id:id, index:index};
       //console.log(JSON.stringify(data));
       if ( id == 'lines' || id == 'preface' ) {
          new_line_after(data);
       } else {
          $(obj).blur();
       }
    }
}

/*
 * 获取文字对应的拼音，并生成相应的HTML
 * 服务器返回的内容如下：
 * dan_pinyin: 数组 元素是对应汉字的拼音字符串 
 * duo_pinyin: 数组 元素是对应汉字的所有读音组成的数组
 */
function get_pinyin(param) {
    let id = param.id, uuid = param.uuid, index = param.index, text = param.text;
    let url = "/v1/pinyin";
    let display_id = `#${uuid}.wz_dp`;
    if ( text.trim().length == 0 ) {
        if ( id in prepo && index in prepo[id] ) prepo[id][index] = {};
        $(display_id).html('');
        return;
    }
    $.post(url, {_xsrf:$.cookie('_xsrf'), text:text})
      .done(function(data) {
          let html = '';
          let pinyin = JSON.parse(data);
          // 更新缓存
          if (!(id in prepo)) prepo[id] = [];
          prepo[id][index] = {};
          prepo[id][index]['text'] = text;
          prepo[id][index]['dan_pinyin'] = pinyin.dan_pinyin;
          prepo[id][index]['duo_pinyin'] = pinyin.duo_pinyin;
          // 生成相应的HTML代码
          let p = {id:id, index:index};
          Object.assign(p, prepo[id][index]);
          html += gen_pinyin_html(p);
          // 显示在相应的输出区域
          $(display_id).html(trans_text(html));
          if ( text.trim().length > g_linelen ) $(display_id).css({'text-indent':'2em', 'text-align':'left'});
          // 添加多音字事件处理器 
          $(display_id).each(function(dyz_index, dyz_container) {
            dyz_event_handler(dyz_container);
          });
      })
      .fail(function(jqXHR, textStatus, errorThrown) {
          console.log("获取拼音失败: " + textStatus + " " + errorThrown );
      });
}

// 获取文字对应的注释，并生成相应的HTML
function get_comment(param) {
    let id = param.id, uuid = param.uuid, index = param.index, text = param.text;
    let url = "/v1/comment"
    let zsdp_id = `#${uuid}.zs_dp`;
    let zsip_id = `#${uuid}.zs_ip`;
    if ( text.trim().length == 0 ) {
        if ( id in prepo && index in prepo[id] ) prepo[id][index] = {};
        $(zsdp_id).html('');
        $(zsip_id).html('');
        return;
    }
    $.post(url, {_xsrf:$.cookie('_xsrf'), text:text})
      .done(function(data) {
          // 合并获得的注释和缓存中的注释
          let comment = merge_comment({id:id,index:index,text:text,comment:JSON.parse(data)});

          // 更新注释显示区 TODO 
          let html = show_comment_v1(comment);
          $(zsdp_id).html(trans_text(html));

          // 更新注释输入区 TODO 
          html = show_comment_v2(comment);

          // 显示在相应的注释输入区域
          $(zsip_id).html(trans_text(html));
      })
      .fail(function(jqXHR, textStatus, errorThrown) {
          console.log("获取注释失败: " + textStatus + " " + errorThrown );
      });
}

// 合并服务器传来的注释和缓存中的注释
function merge_comment(data) {
    let id = data.id;
    let index = data.index;
    let text = data.text;
    let comment = data.comment;
    let cached_comment = 'comment' in prepo ? (id in prepo.comment?(index in prepo.comment[id]?prepo.comment[id][index]:[]):[]):[];
    let temp_comment = cached_comment;
    let updated = false;
    for ( let num in comment ) {
        for ( let key in comment[num] ) {
           if ( has_comment(cached_comment, key) ) continue;
           let obj = new Object();
           obj[key] = comment[num][key];
           append_comment(temp_comment, obj);  
           updated = true;
        } 
    }
    //console.log(id, index, text, comment, cached_comment, temp_comment);
    if(!('comment' in prepo)) prepo['comment'] = {};
    if(!(id in prepo['comment'])) prepo['comment'][id] = [];

    prepo['comment'][id][index] = updated ? temp_comment : cached_comment;
    return temp_comment;
}

function has_comment(comment, key) {
    for ( let index in comment ) {
       if( key in comment[index] ) return true;
    }
    return false;
}

function append_comment(comment, obj) {
    comment.push(obj);
}

// 生成韵律
function get_yl(data) {
    let id = param.id, uuid = param.uuid, index = param.index, text = param.text;
    let yldp_id = `#${uuid}.yl_dp`;
    if ( text.trim().length == 0 ) {
        //if ( id in prepo && index in prepo[id] ) prepo[id][index] = {};
        $(yldp_id).html('');
        return;
    }
    let param = {text:text, dan_pinyin:prepo[id][index]['dan_pinyin']};
    let html = gen_yl_html(param);
    $(yldp_id).html(trans_text(html));
}

// 生成空白诗词
function blank_work(dp=true) {
    var work = {
    id: GUID(),          // 作品唯一标识 
    type:'诗',           // 分类 - 诗、词、曲、文 / shi, ci, qu, wen
    name:'',             // 作品名称
    author:'',           // 作者
    preface:'',          // 序
    category:'五言古诗', // 体裁 - 五言绝句、五言律诗等
    lines:'',            // 正文
    plines:[],           // 正文 - 拼音 单音
    pname:[],            // 作品名称 - 拼音 单音
    pauthor:[],          // 作者 - 拼音 单音
    ppreface:[],         // 序 - 拼音 单音
    dpname:[],           // 作品名称 - 拼音 多音
    dpauthor:[],         // 作者名称 - 拼音 多音
    dppreface:[],        // 序 - 拼音 多音
    dplines:[[]],        // 正文 - 拼音 多音
    tag:[],              // 标签
    url:'',              // 指向百科的链接
    comment:{name:[],preface:[],lines:[]},          // 注释
    analyse:''           // 赏析
    };

    if ( !dp ) ['dpname', 'dpauthor', 'dppreface', 'dplines'].forEach(function(value, index) { delete work[value]; });
    
    return work;
}

// 生成控制作品编辑器界面显示的参数
function set_param(work)
{
   return { 
     name: {config:{input:'input', size:g_linelen, maxlength:50, show_py:true, show_zs:true, show_yl:false, show_yw:false, show_ts:true, wz_ts:'【作品名称】', zs_ts:'【名称注释】', wz_ip_placeholder:'在这里输入作品名称，最多50字', wz_ip_title:'这里是作品名称输入区', wz_dp_title:'单击鼠标左键编辑作品名称', zs_ip_placeholder:'在这里输入作品名称注释', zs_ip_title:'这里是作品名称注释编辑区', zs_dp_title:'单击编鼠标左键辑作品名称注释'}, data:{id:'name', text:work.name, ptext:work.pname, dptext:'dpname' in work?work.dpname:[], comment:'name' in work.comment?work.comment.name:[]}}, 
     author: {config:{input:'input', size:g_linelen, maxlength:10, show_py:true, show_zs:false, show_yl:false, show_yw:false, show_ts:true, wz_ts:'【作者姓名】', wz_ip_placeholder:'在这里输入作者姓名，最多10字', wz_dp_title:'单击鼠标左键编辑作者姓名', wz_ip_title:'这里是作者姓名输入区'}, data:{id:'author', text:work.author, ptext:work.pauthor, dptext:'dpauthor' in work?work.dpauthor:[], comment:[]}},
     type: {config:{input:'select', options:g_work_types, show_py:false, show_zs:false}, data:{id:'type', text:work.type}},
     category: {config:{input:'select', options:category[work.type], show_py:false}, data:{id:'category', text:work.category}},
     preface: {config:{input:'textarea', cols:g_linelen, maxlength:200, show_py:true, show_zs:true, show_yl:false, show_yw:false, show_ts:true, wz_ts:'【序言第1行】', zs_ts:'【序注第1行】', wz_ip_placeholder:'在这里输入序言，最多500字。', wz_dp_title:'单击鼠标左键编辑序言', wz_ip_title:'这里是序言输入区', zs_dp_title:'单击鼠标左键编辑序言注释', zs_ip_title:'序言注释输入区', zs_ip_placeholder:'在这里输入序言注释'}, data:{id:'preface', text:work.preface, ptext:work.ppreface, dptext:'dppreface' in work?work.dppreface:[], comment:'preface' in work.comment?work.comment.preface:[]}}, 
     lines: {config:{input:'textarea', cols:g_linelen, maxlength:200, show_py:true, show_zs:true, show_yl:true, show_yw:true, show_ts:true, ylable:pzable(work.category), wz_ts:'【正文第1行】', zs_ts:'【注释第1行】', yl_ts:'【韵律第1行】', yw_ts:'【译文第1行】', wz_ip_placeholder:'在这里输入正文，最多200字。', wz_ip_title:'正文编辑区', wz_dp_title:'单击鼠标左键编辑正文', yl_title:'韵律编辑区', zs_dp_title:'单击鼠标左键编辑注释', zs_ip_title:'注释输入区', zs_ip_placeholder:'在这里输入注释', yw_ip_title:'译文输入区', yw_ip_placeholder:'在这里输入译文'}, data:{id:'lines', text:work.lines, ptext:work.plines, dptext:'dplines' in work?work.dplines:bdptext(work.lines.split('\n').length), comment:'lines' in work.comment?work.comment.lines:[]}}, 
     tag: {config:{input:'textarea', cols:g_linelen, maxlength:200, show_py:false, show_zs:false, show_yl:false, show_yw:false, show_ts:true, wz_ts:'【作品标签】', wz_ip_placeholder:'在这里输入标签，以空格分隔，最多200字。', wz_dp_title:'单击鼠标左键编辑标签', wz_ip_title:'这里是标签输入区'}, data:{id:'tag', text:work.tag.join(' '), ptext:[],dptext:[], comment:[]}}, 
     analyse: {config:{input:'textarea', cols:g_linelen, maxlength:200, show_py:false, show_zs:false, show_yl:false, show_yw:false, show_ts:true, wz_ts:'【作品赏析】', wz_ip_placeholder:'在这里输入作品赏析，最多200字。', wz_dp_title:'单击鼠标左键编辑作品赏析', wz_ip_title:'这里是作品赏析输入区'}, data:{id:'analyse', text:work.analyse, ptext:[], dptext:[], comment:[]}} 
  }
}
// 根据作品正文行数生成对应的空白多音字数组
function bdptext(num) {
    var array = new Array();
    for ( var index = 0; index < num; index++ ) array[index] = [];
    return array;
}


// 更新用户选择的多音字读音并保存到缓存中
function upd_pinyin(obj) {
    //console.log("Update pinyin ...")
    var id = obj.id.split('_')[0];
    var index = Number(obj.id.split('_')[1]);
    var pindex = Number(obj.id.split('_')[2]);
    var selection = obj.value;
    //console.log(id, index, pindex, selection);

    var dan_pin = prepo[id][index]['dan_pinyin'][pindex];
    if ( selection == dan_pin ) return;
    
    prepo[id][index]['dan_pinyin'][pindex] = selection;
}

// 更新作品类型并保存到缓存中
function upd_type(obj) {
    var id = obj.id.split('_')[0];
    prepo[id] = $.t2s(obj.value);
    list_category(obj.value);
    init_category(obj.value);
}
// 初始化作品
function init_category(type) {
    prepo.category = type in category?(category[type].length?category[type][0]:''):'';
    set_ylable(prepo.category);
}

// 更新作品
function upd_category(obj) {
    let id = obj.id.split('_')[0];
    let category = $.t2s(obj.value);
    prepo[id] = category;
    set_ylable(category);
}

// 判断是否需要显示韵律
function set_ylable(category) {
  let ylable = pzable(category);
  //console.log(`ylable ${ylable}`);
  $('#editor_work_lines').find('.item_sub_container').attr('data_ylable', ylable);
  if (!ylable) {
    $(".yl_container").hide();
  }
}

// 更新作品注释并保存到缓存中
function upd_comment(obj) {
    let uuid = obj.id;
    let index = $(obj).attr('data_index');
    let id = $(obj).attr('data_id');
    let zs_dp = `#${uuid}.zs_dp`;
    let ta = $.t2s(obj.value.trim()).split('\n');
    let to = [];
    let count = 0;
    for ( let num in ta ) {
        if ( ta[num].trim().length == 0 || ta[num].trim().indexOf('：') == -1 ) continue;
        let key = ta[num].split('：')[0].trim();
        let value = ta[num].split('：')[1].trim();
        if ( key.length && value.length ) {
          to[count] = {};
          to[count][key] = value;
          count += 1;
        }
    }
    // 更新注释缓存
    if ( !('comment' in prepo) ) prepo['comment'] = {};
    if ( !(id in prepo.comment) ) prepo['comment'][id] = [];
    prepo['comment'][id][index] = to;
    
    // 更新作品注释显示区
    let html = gen_comment_html(to);
    $(zs_dp).html(trans_text(html));
}

// 生成作品注释的HTML
function gen_comment_html(comment) {
    let html = '';
    for ( let index in comment ) {
        for ( let key in comment[index] ) {
            html += `<span>${cnum[index]}${key}：${comment[index][key]}</span>`;
        }
    }
    return html;
}

// 生成文本对应的拼音
function pin(id, section, text, dan_pinyin, duo_pinyin) {
    let d = {};
    d['text'] = text;
    d['dan_pinyin'] = dan_pinyin;
    d['duo_pinyin'] = duo_pinyin;
    d['id'] = id;
    d['index'] = section;
    return gen_pinyin_html(d);
}

// 生成作品子类列表
function list_category(type) {
    var html='';
    for ( var index in category[type] ) {
        html+=`<option value="${category[type][index]}">${category[type][index]}</option>`;
    }
    $('#category_input').show();
    category[type].length == 0 ? $('#category_input').hide() : $('#category_input').html(trans_text(html));
}

// 生成作品注释的HTML - 用于注释显示区
function show_comment_v1(comment) {
    return gen_comment_html(comment);
}
// 生成作品注释的HTML - 用于注释输入区初始化
function show_comment_v2(comment) {
    let html = '';
    for ( let index in comment ) {
        for ( let key in comment[index] ) {
            html +=`${key}：${comment[index][key]}\n`;
        }
    }
    return html;
}

// 函数：生成显示中文和拼音的HTML文本
// 参数：data.text _ 中文文本 格式为字符串
// 参数：data.dan_pinyin _ 一字一音 格式为数组 数组元素为对应中文的拼音字符串
// 参数：data.duo_pinyin _ 包含多音字的所有读音 格式为数组 数组元素为对应中文的拼音数组
// 注意：通过pypinyin得到的拼音数组中，不包括标点符号，因此文本数组的大小和拼音数组大小不是对应的。比如下面文本中逗号后有空格，文本大小是4，而拼音大小则是2
//       text: "我， 们", dan_pinyin: ["wǒ", "men"], duo_pinyin: [["wǒ"], ["men"]] 
function gen_pinyin_html(data) {
    let html='';
    if ( data.text.length == 0 ) return html;

    let pindex = 0;
    for ( let index in data.text ) {
        if ( is_nonchinese_char(data.text[index]) ) {
            html += `${index == 0 || is_nonchinese_char(data.text[index-1]) ? '' : '</ruby>'}${data.text[index]}`;
            continue;
        }
        html += `${index == 0 || is_nonchinese_char(data.text[index-1]) ? '<ruby>' : '' }${data.text[index]}${mark_pinyin(pindex, data)}${index == data.text.length ? '</ruby>':'' }`;
        pindex += 1;
    } 
    return html;
}

// 函数：生成显示单个汉字拼音的HTML代码, 支持多音字并列出所有读音
// 参数：pindex - 对应拼音数组的下标
// 参数：data.dan_pinyin _ 一字一音 格式为数组 数组元素为对应中文的拼音字符串
// 参数：data.duo_pinyin _ 包含多音字的所有读音 格式为数组 数组元素为对应中文的所有读音 
function mark_pinyin(pindex, data) {
    //let pindex = data.pindex;
    let html = '<rt>';
    if (('duo_pinyin' in data) && (pindex in data.duo_pinyin) && ( typeof data.duo_pinyin[pindex] == 'object') && (data.duo_pinyin[pindex].length > 1 )) {
        html += `<select id="${data.id}_${data.index}_${pindex}">`;
        for ( let num in data.duo_pinyin[pindex] ) {
           html += `<option value="${data.duo_pinyin[pindex][num]}" ${data.duo_pinyin[pindex][num] == data.dan_pinyin[pindex] ? " selected" : ""}> ${data.duo_pinyin[pindex][num]} </option>`;
        }
        html += '</select>';
    } else {
        html += data.dan_pinyin[pindex];
    }
    html += '</rt>';
    return html;
}

// 作品编辑器事件处理器
function editor_event_handler() {
    editor_header_event_handler(); 
    editor_body_event_handler(); 
    editor_footer_event_handler(); 
}

// 设置作品编辑器头部菜单项事件处理器
function editor_header_event_handler() {
    // 菜单项 - 保存
    $('#save_new').on('click', save_new);
    // 菜单项 - 预览和编辑
    $('#preview_edit').on('click', function(){ preview_edit(this); });
    $('#editor_header_close').on('click', function() { $('#modal').trigger('md_close'); $('#modal_content').css('width','50%'); });
}

function editor_footer_event_handler() {
    $('#editor_footer_close').on('click', function() { $('#modal').trigger('md_close'); $('#modal_content').css('width','50%'); });
}

// 设置作品编辑器中部各单元事件处理器
function editor_body_event_handler() {
    ['type','category'].forEach(function(id) {
        let input_id  = '#' + id + '_input';
        $(input_id).on('click', function(event) {
            $(this).focus();
        });
        $(input_id).on('change', function(event) {
            switch(id) {
                case 'type' :
                    upd_type(this);
                    break;
                case 'category' :
                    upd_category(this);
                    break;
            }
        });
    });

    ['name','author','preface','lines','tag','analyse'].forEach(function(id) {
        let container_id = `#editor_work_${id}`;
        $(container_id).find('.item_sub_container').each(function(index, sub_container) {
           item_sub_container_event_handler(sub_container);
        });
    });
}

function item_sub_container_event_handler(sub_container) {
     let id = $(sub_container).attr('data_id');
     let index = $(sub_container).attr('data_index');
     let uuid = sub_container.id;

     // 使能右键上下文菜单
    $(sub_container).on('mouseup', function(event) {
      let ylable = $(sub_container).attr('data_ylable') == 'true'?true:false;
      //console.log("event handler - ylable " + $(sub_container).attr('data_ylable'));
      let menu_items = g_context_menu[id];
      let menu_header = '操作' + $(sub_container).find('.ts').html().replace(/[【】]+/g, '');
      let menu = '<ul>';
      menu_items.forEach(function(cm) {
        let show_menu_item = true;
        let show = false;
        let menu_item = cm.item;
        switch(cm.code) {
          case 'del':
            show_menu_item = $(`#editor_work_${id}`).find('.item_sub_container').length > 1 ? true : false;
            break;
          case 'wz':
            show = $(sub_container).find('.wz_container').find('.wz_ip_container')[0].style.display === 'none'?true:false;
            show_menu_item = $(sub_container).find('.wz_container').find('.wz_ip')[0].value.trim().length?true:false;
            menu_item = show?cm.item:'输入隐藏';
            break;
          case 'yl':
            show_menu_item = ylable;
          case 'zs':
          case 'yw':
            // HTML 'hidden' attribute is not well supported by browser
            show = $(sub_container).find(`.${cm.code}_container`)[0].style.display === 'none'?true:false;
            menu_item = show?`${cm.item}编辑`:`${cm.item}隐藏`;
            break;
        }
        menu += show_menu_item ? `<li onclick="cm_handler(this);$('.context_menu').hide();" data_index="${index}" data_id="${id}" data_code="${cm.code}" data_uuid="${uuid}">${menu_item}</li>` : '';
      });
      menu += '</ul>';
      if ( menu != '<ul></ul>' ) {
        menu = `<header>${menu_header}</header>${menu}`;
        context_menu(event, menu);
      }
    });

    // 文字区事件处理
    $(sub_container).find('.wz_dp').each(function(wzdp_index, wz_dp) {
      $(wz_dp).on('click', function(event) { 
         //$(sub_container).find('.wz_ip_container').toggle(); 
         if ( $(sub_container).find('.wz_ip_container')[0].style.display == 'none' ) {
            $(sub_container).find('.wz_ip_container').show(); 
            $(sub_container).find('.wz_ip_container').find('.wz_ip').focus();
         }
         event.stopPropagation(); 
       });
      //$(wz_dp).on('mouseover', function(event) { event.stopPropagation(); });
    });

    $(sub_container).find('.wz_ip').each(function(wzip_index, wz_ip) {
      //$(wz_ip).on('change', function(event) { event.stopPropagation(); });
      $(wz_ip).on('blur', function(event) { blur(event, this); event.stopPropagation(); });
      $(wz_ip).on('click', function(event) { $(this).focus(); event.stopPropagation(); });
      $(wz_ip).on('keyup', function(event) { key_pressed(event, this); event.stopPropagation(); });
    });

    // 文字区多音字事件处理
    $(sub_container).find('.wz_dp').each(function(dyz_index, dyz_container) {
      dyz_event_handler(dyz_container);
    });

    // 韵律区事件处理
    $(sub_container).find('.yl_dp').find('select').each(function(yl_index, yl) {
      $(yl).on('change', function(event) { upd_yl(this); });
      $(yl).on('mouseover', function(event) { $(yl).attr('title', '点击更改韵律'); event.stopPropagation(); });
      $(yl).on('mouseup', function(event) { event.stopPropagation(); });
    });

    // 注释区事件处理
    $(sub_container).find('.zs_dp').each(function(zsdp_index, zs_dp) {
      $(zs_dp).on('mouseover', function(event) { event.stopPropagation(); });
      $(zs_dp).on('click', function(event) { $(sub_container).find('.zs_ip').toggle(); $(sub_container).find('.zs_ip').focus();  event.stopPropagation(); });
      $(zs_dp).on('mouseup', function(event) { event.stopPropagation(); });
    });
    $(sub_container).find('.zs_ip').each(function(zsip_index, zs_ip) {
      $(zs_ip).on('change', function(event) { upd_comment(this); });
      $(zs_ip).on('blur', function(event) { upd_comment(this); $(this).val().trim().length?$(this).hide():$(this).show(); });
      $(zs_ip).on('mouseup', function(event) { event.stopPropagation(); });
    });

    // 译文区事件处理
    $(sub_container).find('.yw_dp').each(function(ywdp_index, yw_dp) {
      $(yw_dp).on('click', function(event) {
      });
    });
    $(sub_container).find('.yw_ip').each(function(ywip_index, yw_ip) {
      $(yw_ip).on('click', function(event) {
      });
    });
}

// 多音字事件处理
function dyz_event_handler(container) {
    $(container).find('select').each(function(dyz_index, dyz) {
      $(dyz).on('change', function(event) { upd_pinyin(this); });
      $(dyz).on('mouseover', function(event) { $(dyz).attr('title', '点击更改读音'); event.stopPropagation(); });
      $(dyz).on('mouseup', function(event) { event.stopPropagation(); });
      $(dyz).on('click', function(event) { event.stopPropagation(); });
    });
}
  
// 上下文菜单事件处理器
function cm_handler(obj) {
   //console.log("Context Menu Handler ...");
   let uuid = $(obj).attr('data_uuid'), id = $(obj).attr('data_id'), code = $(obj).attr('data_code'), index = $(obj).attr('data_index');
   let data = {uuid:uuid, id:id, index:index};
   //console.log(uuid, id, code, index);
   switch(code) {
     case 'new_before':
       new_line_before(data);
       break;
     case 'new_after':
       new_line_after(data);
       break;
     case 'del':
       del_line(data);
       break;
     case 'wz':
       $(`#${uuid}.item_sub_container`).find('.wz_container').find('.wz_ip_container').each(function(i,container) { $(container).toggle(); }); 
       break;
     case 'yl':
     case 'zs':
     case 'yw':
       $(`#${uuid}.item_sub_container`).find(`.${code}_container`).each(function(i,container) { $(container).toggle(); }); 
       break;
   }
}

function new_line_before(param) {
  //console.log("前插新行");
  //添加页面元素
  let id = param.id, uuid = param.uuid, index = param.index;
  let data = set_param(blank_work(dp=false));
  data[id].data.uuid = GUID();
  data[id].data.index = 0;
  //console.log(JSON.stringify(data[id]));
  let html = template('template_editor_item_sub', data[id]);
  let sub_container = `#${uuid}.item_sub_container`;
  $(sub_container).before(html);
  //更新页面元素相关属性
  upd_item(param);

  $(`#editor_work_${id}`).find('.item_sub_container').each(function(i, container) {
    //console.log(`New uuid: ${data[id].data.uuid} uuid:${container.id}`);
    //为新行添加事件处理
    if ( container.id == data[id].data.uuid ) {
        item_sub_container_event_handler(container);
        $(container).find('.wz_ip').focus();
    }

    // 缺省隐藏韵律、注释和译文编辑区
    ['.yl_container', '.zs_container','.yw_container'].forEach(function(item) {
       $(container).find(item).each(function(j,c) { $(c).hide(); });
    });
  });

  //添加缓存元素
  let item = {text:'', dan_pinyin:[], duo_pinyin:[]};
  if ( id in prepo && prepo[id].length && index in prepo[id] ) {
    prepo[id].splice(index, 1, item, prepo[id][index]);
    prepo.comment[id].splice(index, 1, [], prepo.comment[id][index]);
  }
}

function new_line_after(param) {
  //console.log("后插新行");
  //添加页面元素
  let id = param.id, uuid = param.uuid, index = param.index;
  let data = set_param(blank_work(dp=false));
  data[id].data.uuid = GUID();
  data[id].data.index = 0;
  //console.log(JSON.stringify(data[id]));
  let html = template('template_editor_item_sub', data[id]);
  let sub_container = `#${uuid}.item_sub_container`;
  $(sub_container).after(html);

  //更新页面元素相关属性
  upd_item(param);

  $(`#editor_work_${id}`).find('.item_sub_container').each(function(i, container) {
    //为新行添加事件处理
    //console.log(`New uuid: ${data[id].data.uuid} uuid:${container.id}`);
    if ( container.id == data[id].data.uuid ) {
       item_sub_container_event_handler(container);
       $(container).find('.wz_ip').focus();
    }
    // 缺省隐藏韵律、注释和译文编辑区
    ['.yl_container', '.zs_container','.yw_container'].forEach(function(item) {
       $(container).find(item).each(function(j,c) { $(c).hide(); });
    });
  });

  //添加缓存元素
  let item = {text:'', dan_pinyin:[], duo_pinyin:[]};
  if ( id in prepo && prepo[id].length && index in prepo[id] ) {
    prepo[id].splice(index, 1, prepo[id][index], item);
    prepo.comment[id].splice(index, 1, prepo.comment[id][index], []);
  }
}

function del_line(param) {
  //console.log("删除此行");
  //删除页面元素
  let id = param.id, uuid = param.uuid, index = param.index;
  let sub_container = `#${uuid}.item_sub_container`;
  $(sub_container).remove();
  //更新页面元素相关属性
  upd_item(param);
  //删除缓存元素
  if ( id in prepo &&  prepo[id].length && index in prepo[id] ) {
    prepo[id].splice(index, 1);
    prepo.comment[id].splice(index, 1);
  }
}

// 更新条目属性，仅针对支持上下文菜单的条目
function upd_item(param) {
  let container_id = `#editor_work_${param.id}`;
  $(container_id).find('.item_sub_container').each(function(index, sub_container) {
    $(sub_container).attr('data_index', index);
    $(sub_container).find('[data_index]').each(function(num, container) {
       $(container).attr('data_index', index);
     });
    $(sub_container).find('.ts').each(function(num, ts) {
        let html = $(ts).html();
        html = html.replace(REGNUM, index+1);
        $(ts).html(html);
    });
  });
}

function show_wz_html(param) {
  let html = '';
  if ( param.config.show_py ) {
    let data = {};
    data.text = param.data.text;
    data.dan_pinyin = param.data.ptext;
    data.duo_pinyin = param.data.dptext;
    data.id = param.data.id;
    data.index = param.data.index;
    //console.log(JSON.stringify(data));
    html = gen_pinyin_html(data);
  } else {
    html = param.data.text;
  } 
  return trans_text(html);
}

function show_zs_html(param) {
  let zs = param.data.comment;
  let html = gen_comment_html(zs);  
  return trans_text(html);
}

function show_yl_html(param) {
  let data = {text:param.data.text, dan_pinyin: param.data.ptext, duo_pinyin:param.data.dptext};
  return gen_yl_html(data);
}

function show_yw_html(param) {
  return param.data.text; 
}

function gen_yl_html(data) {
    let html = '';
    if ( data.text.length == 0 ) return html;
    let pindex = 0;
    for ( let index in data.text ) {
        if ( is_nonchinese_char(data.text[index]) ) {
            html += `${index == 0 || is_nonchinese_char(data.text[index-1]) ? '' : '</ruby>'}${data.text[index]}`;
            continue;
        }
        html += `${index == 0 || is_nonchinese_char(data.text[index-1]) ? '<ruby>' : ''}${data.text[index]}${mark_yl(pindex, data)}${index == data.text.length ? '</ruby>':''}`;
        pindex += 1;
    }
    return html;
}

function mark_yl(pindex, data) {
    let html = `<rt><select id="${data.id}_${data.index}_${pindex}">`;
    g_yl.forEach(function(item, num) {
       html += `<option value="${item}" ${ item == getpz(data.dan_pinyin[pindex]) ? ' selected' : ''}> ${item} </option>`;
    });
    html += '</select></rt>';
    return html;
}

template.helper('mylog', function(text) {
/*
   console.log("My log ...");
   if ((typeof text) == 'string' ) {
    console.log(text);
   } else {
    console.log(JSON.stringify(text));
  }
*/
});

// 模板辅助函数，判断是汉字还是标点符号
template.helper('nonchinese_char', function(text) {
    return is_nonchinese_char(text);
});

// 模板辅助函数 - 生成显示选项列表的HTML代码
template.helper('list_options', function(options, selected) {
    var html='';
    for (index in options ) {
       html += `<option value="${options[index]}" ${options[index] == selected ? 'selected' : ''}> ${options[index]}</option>`;
    }
    return html;
});
// 模板辅助函数 - 生成显示输出区的HTML代码
// 模板辅助函数 - 生成代表真假的字符

// 模板辅助函数 - 多行输入框行数 
template.helper('count_rows', function(text) {
   return count_rows(text);
});

template.helper('GUID', function() {
    return GUID();
});

template.helper('show_wz_html', function(param) {
  return show_wz_html(param);
});
template.helper('show_zs_html', function(param) {
  return show_zs_html(param);
});
template.helper('show_yl_html', function(param) {
  return show_yl_html(param);
});

template.helper('show_yw_html', function(param) {
  return show_yw_html(param);
});

template.helper('replace_num', function(text, num) {
  return text.replace(REGNUM, num);
});
</script>

{# 诗词编辑界面模版 总体布局 #}
<script id="template_editor" type="text/html">
  <div id="editor_header" class="modal_header editor_header"  > <% include('template_editor_header') %> </div> 
  <div id="editor_body"   class="modal_body editor_body"      > <% include('template_editor_body')   %> </div> 
  <div id="editor_footer" class="modal_footer editor_footer"  > <% include('template_editor_footer') %> </div> 
</script>

{# 诗词编辑界面模版：编辑界面头部区 显示功能按钮 #}
<script id="template_editor_header" type="text/html">
  <div class="editor_menu_container">
    <ul class="editor_menu">
    <li><span class="editor_menu_item" title="保存作品" id="save_new" > 保存 </span></li>
    <li><span class="editor_menu_item" title="预览作品" id="preview_edit" > 预览 </span></li>
    </ul>
  </div>
  <div>
    <span id="editor_header_close" class="modal_close" title="关闭此编辑界面">关闭</span>
  </div>
</script>

{# 诗词编辑界面模版：编辑界面脚部区 显示关闭按键 #}
<script id="template_editor_footer" type="text/html">
  <span id="editor_footer_close" class="modal_close" title="关闭此编辑界面">关闭</span>
</script>

{# 诗词编辑界面模版：编辑界面主体区 显示诗词各项编辑界面 #}
<script id="template_editor_body" type="text/html">
  <div id="editor_work_type" class="editor_item_container">     {# 子容器1：分类 #}
    <% include('template_editor_type') %>
  </div>
  <div id="editor_work_name" class="editor_item_container">     {# 子容器2：作品名称 #}
    <% include('template_editor_item', name) %>
  </div>
  <div id="editor_work_author" class="editor_item_container">   {# 子容器3：作者 #}
    <% include('template_editor_item', author) %>
  </div>
  <div id="editor_work_preface" class="editor_item_container">  {# 子容器4：序 #}
    <% include('template_editor_item', preface) %>
  </div>
  <div id="editor_work_lines" class="editor_item_container">     {# 子容器5：原文 #}
    <% include('template_editor_item', lines) %>
  </div>
  <div id="editor_work_tag" class="editor_item_container">      {# 子容器6：标签 #}
    <% include('template_editor_item', tag) %>
  </div>
  <div id="editor_work_analyse" class="editor_item_container">  {# 子容器7：赏析 #}
    <% include('template_editor_item', analyse) %>
  </div>
</script>

<script id="template_editor_type" type="text/html">
  <div id="" class="editor_item_output">
  </div>
  <div class="editor_item_input editor_item_type">
    <% include('template_editor_select', type) %>
    <% include('template_editor_select', category) %>
  </div>
</script>

<script id="template_editor_select" type="text/html">
<div>
  <select id="<%=# data.id %>_input" <% if (config.options.length == 0 ) { %>hidden<% } %>>
     <%=# list_options(config.options, data.text) %> 
  </select>
</div>
</script>

{# 诗词编辑界面模版：编辑界面主体区 单项编辑界面 #}
<script id="template_editor_item"  type="text/html">
<% data.text.split('\n').forEach(function(item, index) { %>
  <% var param = {data:{uuid:GUID(), id:data.id, index:index, text:item, ptext: index in data.ptext?data.ptext[index]:[], dptext:index in data.dptext?data.dptext[index]:[], comment:index in data.comment?data.comment[index]:[]}, config:config}; %>
  <% include('template_editor_item_sub',param) %>
<% }); %>
</script>

<script id="template_editor_item_sub"  type="text/html">
<% var param = {data:data,config:config}; %>
<div class="item_sub_container" id="<%=# data.uuid %>" data_id="<%=# data.id %>" data_index="<%=# data.index %>" data_ylable="<%=# config.ylable?'true':'false' %>">
  <% include('template_editor_item_wz', param) %>
  <% if ( config.show_yl ) include('template_editor_item_yl', param) %>
  <% if ( config.show_zs ) include('template_editor_item_zs', param) %>
  <% if ( config.show_yw ) include('template_editor_item_yw', param) %>
</div>
</script>

{# 单项文字编辑区 #}
<script id="template_editor_item_wz"  type="text/html">
<% var param = {data:data,config:config}; param.data['sub']='wz'; %>
<% var cdata = `id="${ data.uuid }" data_id="${ data.id }" data_index="${ data.index }" data_show_py="${ config.show_py }" data_show_zs="${ config.show_zs }"`; %>
<% var wzip_style = `rows="${count_rows(data.text)}" maxlength="${config.maxlength}" title="${config.wz_ip_title}" placeholder="${config.wz_ip_placeholder}"` %>
<% var wzdp_style = `title="${config.wz_dp_title}" ${config.show_py?'':'hidden'}` %>
<% var wzts = replace_num(config.wz_ts, data.index+1); %>
<div class="wz_container WIS_container">
  {# 文字提示区 #}
  <% if ( config.show_ts ) { %>
  <div class="ts wz_ts" <%=# cdata %> data_sub="wz"><%=# wzts %></div>
  <% } %>
  <div class="WIS_subcontainer">
  {# 文字显示区 #}
  <div class="wz_dp" <%=# cdata %> <%=# wzdp_style %>><%=# show_wz_html(param) %></div>
  {# 文字输入区 #}
  <div class="wz_ip_container">
  <textarea class="wz_ip" <%=# cdata %> <%=# wzip_style %>><%=# data.text %></textarea>
  </div>
  </div>
</div>
</script>

{# 单项韵律编辑区 #}
<script id="template_editor_item_yl"  type="text/html">
<% var param = {data:data, config:config}; param.data['sub']='yl'; %>
<% var ylts = replace_num(config.yl_ts, data.index+1); %>
<% var cdata = `id="${ data.uuid }" data_id="${ data.id }" data_index="${ data.index }"`; %>
<% var yl_dp_style = `title="${config.yw_dp_title}"`; %>
<div class="yl_container WIS_container">
  {# 韵律提示区 #}
  <% if ( config.show_ts ) { %>
  <div class="ts yl_ts" <%=# cdata %> data_sub="yl"><%=# ylts %></div>
  <% } %>
  <div class="WIS_subcontainer">
  {# 韵律显示区输入区合二为一 #}
  <div class="yl_dp yl_ip" <%=# cdata %> <%=# yl_dp_style %>><%=# show_yl_html(param) %></div>
  {# 韵律输入区 
  <div class="yl_ip" <%=# cdata %>></div>
  #}
  </div>
</div>
</script>

{# 单项注释编辑区 #}
<script id="template_editor_item_zs"  type="text/html">
<% var param = {data:data,config:config}; param.data['sub']='zs'; %>
<% var zsts = replace_num(config.zs_ts, data.index+1); %>
<% var cdata = `id="${ data.uuid }" data_id="${ data.id }" data_index="${ data.index }"`; %>
<% var zs_ip_style = `rows="${count_rows(data.text)}" maxlength="${config.maxlength}" title="${config.zs_ip_title}" placeholder="${config.zs_ip_placeholder}"`; %>
<% var zs_dp_style = `title="${config.zs_dp_title}"`; %>
<div class="zs_container WIS_container">
  {# 注释提示区 #}
  <% if ( config.show_ts ) { %>
  <div class="ts zs_ts" <%=# cdata %> data_sub="zs"><%=# zsts %></div>
  <% } %>
  <div class="WIS_subcontainer">
  {# 注释显示区 #}
  <div class="zs_dp" <%=# cdata %> <%=# zs_dp_style %>><%=# show_zs_html(param) %></div>
  {# 注释输入区 #}
  <textarea class="zs_ip" <%=# cdata %> <%=# zs_ip_style %>><%=# data.comment.join('\n') %></textarea>
  </div>
</div>
</script>

{# 单项译文编辑区 #}
<script id="template_editor_item_yw"  type="text/html">
<% var param = {data:data,config:config}; param.data['sub']='yw'; %>
<% var ywts = replace_num(config.yw_ts, data.index+1); %>
<% var cdata = `id="${ data.uuid }" data_id="${ data.id }" data_index="${ data.index }"`; %>
<% var yw_ip_style = `rows="${count_rows(data.text)}" maxlength="${config.maxlength}" title="${config.yw_ip_title}" placeholder="${config.yw_ip_placeholder}"`; %>
<div class="yw_container WIS_container">
  {# 译文提示区 #}
  <% if ( config.show_ts ) { %>
  <div class="ts yw_ts" <%=# cdata %> data_sub="yw" ><%=# ywts %></div>
  <% } %>
  <div class="WIS_subcontainer">
  {# 译文显示区 
  <div class="yw_dp" <%=# cdata %>><%=# show_yw_html(param) %></div>
  #}
  {# 译文输入区显示区合一 #}
  <textarea class="yw_dp yw_ip" <%=# cdata %> <%=# yw_ip_style %>><%=# data.yw %></textarea>
  </div>
</div>
</script> 

{# 作品编辑器显示风格控制区 #}
<style>
.editor_body {
    background-color: #c2c8f6;
    padding: 10px;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
}
.editor_header{
    background-color: #FFF8DC;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
}
.editor_menu {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-items: center;
    list-style: none;
    padding: 0px;
    margin: 0px;
}
.editor_menu li {
  display: inline;
  cursor: pointer;
  text-decoration: none
}
.editor_menu li+li:before {
  padding: 5px;
  color: LightGray;
  content: "|";
}
.editor_menu li:hover {
  font-weight: bold;
}

.editor_footer {
  background-color: #FFF8DC;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
.editor_work_item {
    width: 100%;
}
.editor_item_container {
   width: 100%;
   padding: 5px;
   display: flex;
   flex-direction: column;
   justify-content: flex-start;
   align-items: center;
}
.editor_item {
   width: 100%;
   display: flex;
   flex-direction: row;
   justify-content: space-between;
   align-items: center;
}

.editor_item_output {
  width: 50%;
   flex-direction: column;
   justify-content: flex-start;
   flex-wrap: wrap;
   align-items: center;
}
.editor_item_input {
  width: 50%;
}

.editor_item_type {
   width: 100%;
   display: flex;
   flex-direction: row;
   justify-content: center;
   align-items: center;
}

.item_sub_container {
   width: 100%;
   padding: 5px;
   display: flex;
   flex-direction: column;
   justify-content: flex-start;
   align-items: center;
}

.WIS_container {
   width: 100%;
   display: flex;
   flex-direction: row;
   justify-content: flex-start;
   align-items: center;
}

.ts {
  width: 15%;
  font-size: 14px;
}
.WIS_subcontainer {
   width: 85%;
   display: flex;
   flex-direction: column;
   justify-content: flex-start;
}

.WIS_subcontainer textarea {
}

.item_output {
   width: 100%;
   display: flex;
   flex-direction: column;
   justify-content: center;
   align-items: center;
}

.item_output_container {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}
.item_output_prefix {
   width: 20%;
   font-size: 14px;
}
.output_item {
   width: 80%;
   padding: 5px;
}
.item_comment_container {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}
.item_comment_prefix {
  width: 20%;
  font-size: 14px;
}

.item_comment_display {
  width: 80%;
//  text-align: center;
  font-size: 14px;
  background-color: GhostWhite;
  color: Grey;
}
.item_comment_input {
}

.context_menu li:nth-child(even) {
  background-color: Azure;
}
</style>
